package com.gopay.scheduler.job;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.cps.dao.cbrmb.CbRmbTranAssistDtlDao;
import com.gopay.common.domain.cbrmb.CbRmbTranAssistDtl;
import com.gopay.common.domain.cps.CpsGenPayOrder;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.service.cbrmb.CbRmbPayForCcbService;

/**
 * 
 * @ClassName: CbRmbPayForCcbJob
 * @Description: 跨境人民币 自动结算
 * @author gd.cui
 * @date 2016年6月29日 下午4:27:03 ww.gopay.com.cn Inc.All rights reserved.
 */
public class CbRmbPayForCcbJob extends GopayBaseJob {
    // 日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "cbRmbPayForCcbService")
    private CbRmbPayForCcbService cbRmbPayForCcbService;

    @Resource(name = "cbRmbTranAssistDtlDao")
    private CbRmbTranAssistDtlDao cbRmbTranAssistDtlDao;
    
    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;

    @Override
    protected void doJobInternal() {
        /**
         * 现在是3分钟跑一次
         */
        Date now=new Date();
        if (!isHoliday(now)&&isWorkDay()) {
            logger.info("=======start cbrmb Settlement ===========");
            Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);
            Date nowTime = c.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date11 = new Date(nowTime.getYear(), nowTime.getMonth(), nowTime.getDate(), 11, 00);
            Date date330 = new Date(nowTime.getYear(), nowTime.getMonth(), nowTime.getDate(), 15, 30);
            // String hql = "from CbRmbTranAssistDtl where state=:state";
            // 已经发生退款的汇款类订单不要去报盘了,edit by qld 20160810
            // 在20161109再次修改逻辑，汇款充值的reid=汇款的订单号，汇款充值退款的reid=汇款充值的，所以2个关联获取该笔汇款订单是否发生退款
            // 这个要修改准备，在报盘表中加上一个状态03，报盘订单发生退款
            //20170207加上拨款订单成功的条件 add by qld 
            String hql = "from  CbRmbTranAssistDtl a where not exists"
                    + "(select 1 from CpsGenMainOrder t where a.gopayOrderId=t.relevanceGopayOrderId and t.gopayIntTxnCd in('01728','01730') and t.txnStaCd!='20003') "
                    + "and not exists"
                    + "(select 1 from CpsGenMainOrder t,CpsGenMainOrder tk where a.gopayOrderId=t.relevanceGopayOrderId and tk.relevanceGopayOrderId=t.gopayOrderId "
                    + "and tk.gopayIntTxnCd='01733' and tk.txnStaCd!='20003') and a.state=:state "
                    //+ "and exists(select 1 from CpsGenMainOrder t where a.gopayOrderId=t.gopayOrderId and t.gopayTxnTm<=to_date(:stime,'yyyy-MM-dd hh24:mi:ss') )"
                    +" and not  exists(select 1 from CbRmbForceRefundRecord f where f.gopayOrderId=a.gopayOrderId and f.reviewStatus='2')    "
                    + " and exists(select 1 from CpsGenMainOrder t,CpsGenPayOrder p where t.relevanceGopayOrderId=a.gopayOrderId and t.gopayIntTxnCd='01734' and" +
                    " t.gopayOrderId=p.gopayOrderId and p.payStat='04' )"
                    +" and  a.tranType!='01725'  ";//最后一行是排除汇款的线下付款订单，线下汇款订单不去报盘
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("state", "01");
           // if (hour == 11 && minute == 30) {// 11:30的
               // param.put("stime", sdf.format(date11));
                List<CbRmbTranAssistDtl> cbRmbTranAssistDtls = cbRmbTranAssistDtlDao.findByHql(hql, param);
                logger.error("========待报盘数据为" + cbRmbTranAssistDtls.size() + "条=====");
                for (CbRmbTranAssistDtl tranAssistDtl : cbRmbTranAssistDtls) {
                    logger.error("待报盘数据：" + ToStringBuilder.reflectionToString(tranAssistDtl));
                    cbRmbPayForCcbService.payForCcb(tranAssistDtl);
                }
            //} else if (hour == 16 && minute == 0) {//
//                param.put("stime", sdf.format(date330));
//                List<CbRmbTranAssistDtl> cbRmbTranAssistDtls = cbRmbTranAssistDtlDao.findByHql(hql, param);
//                logger.error("========待报盘数据为" + cbRmbTranAssistDtls.size() + "条=====");
//                for (CbRmbTranAssistDtl tranAssistDtl : cbRmbTranAssistDtls) {
//                    logger.error("待报盘数据：" + ToStringBuilder.reflectionToString(tranAssistDtl));
//                    cbRmbPayForCcbService.payForCcb(tranAssistDtl);
//                }

           // }else{
//                logger.info("这个时间不跑定时任务去报盘");
//            }

        } else {
            logger.info(" ======= 非工作时间，抱歉哦！ ===========");

        }
    }

    private boolean isWorkDay() {
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
       //临时改成20点，生产现在时16点截止
            if (hour >= 9 && hour <16) {
                return true;
            }

        return false;
    }

    /**
     * 是否为节假日,暂时就用节假日表01类型
     * @return
     */
    public boolean isHoliday(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        String year = DateUtils.format(calendar.getTime(), "yyyy");
        String month = DateUtils.format(calendar.getTime(), "M");
        String day = DateUtils.format(calendar.getTime(), "d");
        
        StringBuilder sb = new StringBuilder();
        
        sb.append(" select t.year, t.month, t.holidays ");
        sb.append("   from holiday_information t ");
        sb.append("  where 1 = 1       ");
        sb.append("    and ','||t.holidays||',' like :holidays ");
        sb.append("    and t.month=:month ");
        sb.append("    and t.year=:year ");
        sb.append("    and t.holiday_type = '01' ");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("holidays", "%,"+day+",%");
        map.put("month", month);
        map.put("year", year);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);

        return rsList != null && rsList.size() > 0;
    }
    
}
